package s63.kong.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import s63.kong.shop.pojo.AjaxResult;
import s63.kong.shop.pojo.User;
import s63.kong.shop.service.UserService;

@RestController
@RequestMapping("users")
@RequiredArgsConstructor//构造常量
public class UserController {
    private final UserService userService;

    @GetMapping
    @PreAuthorize("hasAuthority('user:list')")
    public AjaxResult list(User user,Integer pageNo,Integer pageSize){
        LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(User.class)
                .like(StringUtils.hasText(user.getNickName()),User::getNickName,user.getNickName())
                .eq(user.getDeptId() != null,User::getDeptId,user.getDeptId());

        Page<User>page = userService.page(Page.of(pageNo, pageSize), queryWrapper);
        return AjaxResult.ok(page);
    }

    @PostMapping
    @PreAuthorize("hasAuthority('user:add')")
    public AjaxResult add(@RequestBody User user){
        userService.save(user);
        return AjaxResult.ok();
    }

    @GetMapping("/{userId}")
    @PreAuthorize("hasAuthority('user:list')")
    public AjaxResult get(@PathVariable Integer userId){
        return AjaxResult.ok(userService.getById(userId));
    }


    @PutMapping
    @PreAuthorize("hasAuthority('user:update')")
    public AjaxResult update(@RequestBody User user){
        userService.updateById(user);
        return AjaxResult.ok();
    }

    @DeleteMapping("/{userId}")
    @PreAuthorize("hasRole('manager')")
    public AjaxResult del(@PathVariable Integer userId){
        return AjaxResult.ok(userService.removeById(userId));
    }
}
